<template>
  <div>
    <div class="app-container">
      <el-card shadow="never">
        <!-- 搜索 -->
        <el-form
          :inline="true"
          :model="requestParameters"
          ref="requestParameters"
        >
          <div class="filter-container">
            <!-- 关键字 -->
            <el-form-item label="关键字">
              <el-input
                v-model="requestParameters.keyword"
                placeholder="根据文章标题进行搜索"
              ></el-input>
            </el-form-item>
            <!-- 状态 -->
            <el-form-item
              label="状态"
              class="check-state"
            >
              <el-select
                v-model="requestParameters.state"
                placeholder="请选择"
              >
                <el-option
                  label="启用"
                  value="1"
                ></el-option>
                <el-option
                  label="禁用"
                  value="0"
                ></el-option>
              </el-select>
            </el-form-item>
            <!-- 按钮搜索 和重置 -->
            <el-form-item>
              <el-button
                class="filter-item"
                size="small"
                @click="resetForm"
              >清除</el-button>
              <el-button
                class="filter-item"
                size="small"
                type="primary"
                icon="el-icon-search"
                @click="handleFilter"
              >搜索</el-button>
            </el-form-item>
            <el-button
              class="filter-item fr"
              size="small"
              style="margin-left: 10px;"
              @click="addArtBtn"
              type="success"
              icon="el-icon-edit"
            >新增技巧</el-button>
          </div>
        </el-form>
        <!-- end -->
        <!-- 信息提示 -->
        <el-alert
          v-if="alertText !== ''"
          :title="alertText"
          type="info"
          class="alert"
          :closable="false"
          show-icon
        ></el-alert>
        <!-- end -->
        <!-- 数据 -->
        <el-table
          :data="articleList"
          v-loading="listLoading"
          element-loading-text="正在加载中"
          fit
          highlight-current-row
          style="width: 100%"
        >
          <el-table-column
            align="center"
            width="75"
            label="序号"
            type="index"
          >
            <!-- <template slot-scope="scope">
              <span>{{scope.row.id}}</span>
            </template> -->
          </el-table-column>
          <el-table-column
            align="center"
            width="300"
            label="文章标题"
          >
            <template slot-scope="scope">
              <span>{{scope.row.title}}</span>
            </template>
          </el-table-column>
          <el-table-column
            width="150"
            align="center"
            label="阅读数"
          >
            <template slot-scope="scope">
              <span>{{scope.row.visits}}</span>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="录入人"
            width="150"
          >
            <template slot-scope="scope">
              <span>{{scope.row.username}}</span>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="录入时间"
            width="200"
          >
            <template slot-scope="scope">
              <span>{{scope.row.createTime | parseTimeByString('{y}-{m}-{d} {h}:{i}:{s}')}}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="状态"
            prop="state"
            align="center"
          >
            <template v-slot="{row}">
              <span v-if="row.state===1">已禁用</span>
              <span v-else>已启用</span>
            </template>
          </el-table-column>
          <!-- 按钮 -->
          <el-table-column
            label="操作"
            fixed="right"
            width="280"
            align="center"
          >
            <template v-slot="{row}">
              <el-button
                type="text"
                @click="previewBtn(row)"
              >预览</el-button>
              <el-button
                type="text"
                @click="changeState(row)"
              >
                <span v-if="row.state===1">启用</span>
                <span v-else>禁用</span>
              </el-button>
              <el-button
                type="text"
                @click="updateShow(row)"
                :disabled='row.state!==0'
              >修改</el-button>
              <el-button
                type="text"
                :disabled='row.state!==0'
                @click="removeBtn(row)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- end -->
        <!-- 分页 -->
        <div class="pagination">
          <PageTool
            :paginationPage="requestParameters.page"
            :paginationPagesize="requestParameters.pagesize"
            :total="total"
            @pageChange="handleCurrentChange"
            @pageSizeChange="handleSizeChange"
          ></PageTool>
        </div>
        <!-- end -->
      </el-card>
      <!-- 放置预览弹出层 -->
      <el-dialog
        title="预览文章"
        :visible="isPreviewDialog"
        @close="isPreviewDialog = false"
      >
        <h4>{{articleMsg.title}}</h4>

        {{articleMsg.createTime}} {{articleMsg.visits}}

        <!-- <div class="preview-content"> -->
        <div v-html="articleMsg.articleBody">
        </div>
        <!-- </div> -->
      </el-dialog>
      <!-- 放置修改文章详情或新增文章弹出层 -->
      <el-dialog
        :title="formData.id ? '修改文章' : '新增文章'"
        :visible="isUpdateDialog"
        @close="closeDialog"
      >
        <el-form
          ref="roleFormRef"
          :model="formData"
          :rules="rules"
          size="medium"
          label-width="100px"
        >
          <el-form-item
            label="文章标题"
            prop="title"
          >
            <el-input
              v-model="formData.title"
              placeholder="请输入单行文本文章标题"
              clearable
              :style="{width: '100%'}"
            >
            </el-input>
          </el-form-item>
          <el-form-item
            label="文章内容"
            prop="articleBody"
          >
            <template>
              <div class="local-quill-editor">
                <quill-editor
                  ref="myLQuillEditor"
                  v-model="formData.articleBody"
                  :options="editorOption"
                  class="editor"
                >
                  <!-- @blur="onEditorBlur"
                  @focus="onEditorFocus"
                  @change="onEditorChange" -->
                </quill-editor>
              </div>
            </template>
          </el-form-item>
          <el-form-item
            label="视频地址"
            prop="videoURL"
          >
            <el-input
              v-model="formData.videoURL"
              placeholder="请输入视频地址"
              clearable
              :style="{width: '100%'}"
            >
            </el-input>
          </el-form-item>
        </el-form>
        <div slot="footer">
          <el-button @click="isUpdateDialog = false">取消</el-button>
          <el-button
            type="primary"
            @click="updateBtn"
          >确定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<style rel="stylesheet/scss" lang="scss" scoped>
.alert {
  margin: 10px 0px;
}
.pagination {
  margin-top: 10px;
  text-align: right;
}
.filter-container {
  .check-state {
    margin-left: 46px;
  }
  .preview-content {
    width: 100%;
    overflow: hidden !important;
  }
}
.local-quill-editor {
  overflow: hidden;
  .editor {
    height: 300px;
    padding-bottom: 50px;
  }
}
</style>

<style>
.el-table th {
  background-color: #fafafa;
}
.el-table th.is-leaf {
  border-bottom: 2px solid #e8e8e8;
}
/* .el-form-item {
  margin-bottom: 0;
} */
.disabled td {
  background-color: #f9f9f9;
  color: #c1c1c1;
}
.disabled .el-button--primary,
.disabled .el-button--danger {
  background-color: #dbdada;
  border: 1px solid #dbdada;
  color: #999;
  cursor: not-allowed;
}
</style>

<script>
// import { simple } from '@/api/base/permissions'
// import { list, remove, detail } from '@/api/base/users'
import { list, detail, add, remove, update, changeState } from '@/api/hmmm/articles'
import PageTool from '../../module-manage/components/page-tool.vue'
// 引入样式和quillEditor
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'
// 工具栏配置项
const toolbarOptions = [
  ['bold', 'italic', 'underline', 'strike'],
  [{ header: 1 }, { header: 2 }],
  [{ list: 'ordered' }, { list: 'bullet' }],
  ['link', 'image']
]

export default {
  name: 'base-users',
  // 注册 quillEditor
  components: {
    quillEditor, PageTool
  },
  data () {
    return {
      stateText: '禁用',
      status: null,
      // 搜索表单信息
      formInline: {
        keyword: '',
        state: ''
      },
      // 文章列表相关
      articleList: [],
      listLoading: false,
      isPreviewDialog: false,
      isUpdateDialog: false,
      alertText: '',
      total: null,
      requestParameters: {
        page: 1,
        pagesize: 10
        // username: this.username
      },
      isAdd: false,
      articleMsg: {},
      formData: {
        title: undefined,
        videoURL: undefined,
        articleBody: undefined
      },
      rules: {
        title: [{
          required: true,
          message: '请输入文章标题',
          trigger: 'blur'
        }],
        videoURL: [],
        articleBody: [{
          required: true,
          message: '请输入文章标题',
          trigger: 'blur'
        }]
      },
      // 富文本框
      content: '',
      editorOption: {
        modules: {
          toolbar: toolbarOptions
        },
        theme: 'snow',
        placeholder: '请输入正文'
        // Some Quill optiosn...
      }
      // userId: null,

    }
  },
  computed: {},
  methods: {
    // 获取文章详情
    async getList () {
      this.listLoading = true
      try {
        const { data } = await list(this.requestParameters)
        // console.log(data.items)
        this.articleList = data.items
        // console.log(data)
        this.total = data.counts
        this.alertText = `共 ${data.counts} 条记录`
        this.total = data.counts
      } catch (error) {
        this.$message.fail('抱歉，出错了')
      }
      this.listLoading = false
    },
    // 点击预览文章详情
    async previewBtn (data) {
      // console.log('预览')
      this.isPreviewDialog = true
      try {
        // 请求文章详情
        const res = await detail(data)
        this.articleMsg = res.data
      } catch (error) {
        this.$message.fail('抱歉，出错了')
      }
    },
    // 重置搜索框
    resetForm () {
      this.requestParameters.keyword = ''
      this.requestParameters.state = ''
    },
    // 修改文章弹层显示
    async updateShow (data) {
      // console.log('修改')
      try {
        // 文章详情回显
        // 请求文章详情
        const res = await detail(data)
        this.formData = res.data
        this.articleMsg = res.data
        this.isUpdateDialog = true
      } catch (error) {
        this.$message.fail('抱歉，出错了')
      }
    },
    // 新增文章弹出层显示
    addArtBtn () {
      this.isUpdateDialog = true
      // 修改添加状态为true 方便判定是否为添加还是修改
      this.isAdd = true
    },
    // 修改文章 和 新增文章
    async updateBtn () {
      try {
        if (this.isAdd) {
        // 执行新增
          await add(this.formData)
          this.$message.success('新增成功')
          // 重新加载页面
          this.getList()
        } else {
        // 执行修改
          await update(this.articleMsg)
          this.$message.success('修改成功')
        }
      } catch (error) {
        this.$message.error('抱歉，出错了')
      }
      this.isUpdateDialog = false
      this.isAdd = false
    },
    // 删除文章
    removeBtn (data) {
      // 确认删除？
      this.$confirm('此操作将永久删除用户 ' + ', 是否继续?', '提示', {
        type: 'warning'
      }).then(async () => {
        try {
          // 调用删除接口
          await remove(data)
          this.$message.success('删除成功！')
          // 重新加载列表
          this.getList()
        } catch (error) {
          this.$message.fail('出错了')
        }
      }).catch(() => {
        // 取消删除
      })
    },
    // 关闭弹层
    closeDialog () {
      this.isUpdateDialog = false
      // 重置表单
      // this.$refs.roleFormRef.resetFields()
      this.formData = {}
    },
    // 搜索文章
    async handleFilter () {
      //
      this.requestParameters.page = 1
      this.listLoading = true
      const { data } = await list(this.requestParameters)
      console.log(data.items)
      this.alertText = `共 ${data.counts} 条记录`
      this.articleList = data.items
      this.listLoading = false
    },
    // 分页组件事件
    // 每页显示信息条数
    handleSizeChange (val) {
      this.requestParameters.pagesize = val
      if (this.requestParameters.page === 1) {
        this.getList()
      }
    },
    // 进入某一页
    handleCurrentChange (val) {
      this.requestParameters.page = val
      this.getList()
    },
    // 点击状态切换（1启用，0禁用）
    async changeState (val) {
      // 判断是在禁用状态（state === 0）还是启用状态（state === 1）
      if (val.state === 1) {
        val.state = 0
        this.status = '禁用'
      } else {
        val.state = 1
        this.status = '启用'
      }
      var data = {
        id: val.id,
        state: val.state
      }
      try {
        await changeState(data)
        this.$message.success('操作成功！')
      } catch (err) {
        this.$message('操作失败！')
      }
    }
  },
  // 创建完毕状态
  created () {
    // 读取数据
    this.getList()
    // 键盘enter操作
    // var lett = this
    // document.onkeydown = function (e) {
    //   var key = window.event.keyCode
    //   if (key === 13) {
    //     lett.handleFilter(this.requestParameters)
    //   }
    // }
  }

}
</script>
